package com.chl.legou.order.listener;

import com.chl.legou.order.service.OrderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author chlong
 * @date 2022/3/16
 */
@Component
@RabbitListener(queues = "${mq.pay.queue.order}")
public class OrderUpdateListener {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;

    @RabbitHandler
    public void handlerData(String msg){
        //1.接收消息(有订单的ID 有transaction_id )
        Map<String,String> map = null;
        try {
            map = objectMapper.readValue(msg,Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //更新对应的订单状态
        if (map != null){
            if (map.get("trade_status").equals("TRADE_SUSSESS")){
                orderService.updateStatus(map.get("out_trade_no"),map.get("transaction_id"));
            }else {
               //TODO 支付失败  删除订单
                rabbitTemplate.convertAndSend(env.getProperty("mq.order.exchange.ttl"),env.getProperty("mq.order.routing.ttl"),map.toString());
            }
        }
    }
}
